package com.lalameow.loginbylogingate.protocol;

import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import com.comphenix.protocol.wrappers.WrappedGameProfile;
import com.lalameow.loginbylogingate.LoginByLoginGate;
import com.lalameow.packet.enumtype.VailPlayerState;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/11
 * 时间: 23:56
 * 功能：请进行修改
 */
public class LoginStarPackHandler extends PacketAdapter {
    public static KeyPair keyPair;
    public LoginStarPackHandler() {
        super(LoginByLoginGate.plugin, ListenerPriority.HIGHEST,  PacketType.Login.Client.START);
        try
        {
            KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
            keypairgenerator.initialize(1024);
            keyPair= keypairgenerator.generateKeyPair();
        }
        catch (NoSuchAlgorithmException nosuchalgorithmexception)
        {
            nosuchalgorithmexception.printStackTrace();
        }
    }

    @Override
    public void onPacketSending(PacketEvent event) {
        super.onPacketSending(event);
    }

    @Override
    public void onPacketReceiving(final PacketEvent event) {
        String playerName=null;
        try {
            WrappedGameProfile gameProfile=event.getPacket().getGameProfiles().read(0);
            playerName=gameProfile.getName();
            CountDownLatch countDownLatch= LoginByLoginGate.plugin.getLoginGateClient().vaildPlayer(playerName);
            boolean isTimeout=countDownLatch.await(20, TimeUnit.SECONDS);
            if(!isTimeout){
                LoginByLoginGate.plugin.getLogger().info(ChatColor.RED+"玩家【"+playerName+"】登录超时，拒绝连接");
                this.diconnectPlayer(event.getPlayer(),ChatColor.RED+"登录超时，请重新登录。");
            }
            VailPlayerState vailPlayerState=LoginByLoginGate.playerCache.getIfPresent(playerName);
            if(vailPlayerState!=null){
                switch (vailPlayerState){
                    case SUCESS:
                        LoginByLoginGate.plugin.getLogger().info(ChatColor.GREEN+"玩家【"+playerName+"】校验通过，正在登录中。。");
                        break;
                    case NOAUTH:
                        LoginByLoginGate.plugin.getLogger().info(ChatColor.RED+"玩家【"+playerName+"】登录网关没有查询到此用户，拒绝连接");
                        this.diconnectPlayer(event.getPlayer(),ChatColor.RED+"用户未认证授权，请使用本服务器专用客户端！");
                        break;
                    case NOLOGIN:
                        this.diconnectPlayer(event.getPlayer(),ChatColor.RED+"请使用科学的登录方式登录!");
                        LoginByLoginGate.plugin.getLogger().info(ChatColor.RED+"获取玩家【"+playerName+"】没有登录，请使用本服务器专用客户端。");
                        break;
                    default:

                }
            }else {
               this.diconnectPlayer(event.getPlayer(),ChatColor.RED+"请使用科学的登录方式登录!");
                LoginByLoginGate.plugin.getLogger().info(ChatColor.RED+"获取玩家【"+playerName+"】变量为空，拒绝连接。。");
            }

        } catch ( InterruptedException | InvocationTargetException e) {
            e.printStackTrace();
            try {
                diconnectPlayer(event.getPlayer(),ChatColor.RED+"登录异常！重新连接或者请联系管理员。。");
                LoginByLoginGate.plugin.getLogger().info(ChatColor.RED+"获取玩家【"+playerName+"】异常！！，拒绝连接。。");
            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            }
        }
    }
    private void diconnectPlayer(Player player,String reson) throws InvocationTargetException {

        PacketContainer packetContainer=LoginByLoginGate.plugin.getProtocolManager().createPacket(PacketType.Login.Server.DISCONNECT);
        packetContainer.getChatComponents().write(0, WrappedChatComponent.fromText(reson));
        LoginByLoginGate.plugin.getProtocolManager().sendServerPacket(player,packetContainer);
    }
}
